import json
import os
import random
import re
import time

import requests
from flask import Flask, jsonify, request
from flask_cors import CORS

app = Flask(__name__)

# 允许跨域请求
CORS(app, supports_credentials=True)


def parse_html(html):
    # 解析 HTML 内容，提取新闻标题和链接
    news = []
    for i in re.findall(r'<div class=\"time hidden-xs\"> <span>([\s\S]+?)<p class="hidden-xs"></p>', html):
        post_ym = re.findall(r'(\d{4}-\d{2})<', i)
        post_ym = post_ym[0].strip() if post_ym else ""
        post_d = re.findall(r'<span class="day">(\d+?)</span>', i)
        post_d = post_d[0].strip() if post_d else ""
        post_title = re.findall(r'<h4> <a href=".*?>(.*?)</a> </h4>', i)
        post_title = post_title[0].strip() if post_title else ""
        post_link = re.findall(r'<div class="cover"> <a href="(.*?)">', i)
        post_link = post_link[0].strip() if post_link else ""
        if not post_link.startswith("http"):
            post_link = "https://gxufl.edu.cn" + post_link

        news.append(
            {
                'id': len(news) + 1,
                "title": post_title,
                "abstract": post_title,
                "content": post_title,
                "link": post_link,
                "date": post_ym + "-" + post_d,
                "author": "gxufl",
            }
        )
    return news


def format_time(time_str):
    # 获取时间戳
    time_stamp = time.mktime(time.strptime(time_str, "%Y-%m-%d %H:%M:%S"))
    return int(time_stamp)


def get_news_from_web():
    urlbase = "https://gxufl.edu.cn/node/38-"
    pages = list(range(1, 40))
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"
    }
    sel_page = random.choice(pages)
    url = urlbase + str(sel_page)
    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        html = response.text
        news = parse_html(html)
        return news
    else:
        print(f"Error: {response.status_code}")
        return []


def read_local_news():
    news_file_path = "news.json"
    try:
        if os.path.exists(news_file_path):
            with open(news_file_path, "r", encoding="utf-8") as f:
                news = f.read().strip()
                news = json.loads(news)
                if time.time() - format_time(news.get("update_time")) > 60:
                    # 如果数据超过60秒未更新，则重新获取
                    news = get_news_from_web()
                    with open(news_file_path, "w", encoding="utf-8") as wf:
                        wf.write(json.dumps(
                            {"news": news, "update_time": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}))
                    return news
                return news.get("news", [])
        else:
            # 如果文件不存在，则获取数据并创建文件
            news = get_news_from_web()
            with open(news_file_path, "w", encoding="utf-8") as wf:
                wf.write(
                    json.dumps({"news": news, "update_time": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}))
            return news
    except FileNotFoundError:
        print(f"Error: {news_file_path} not found.")
        return []


# —— 伪造的内存数据 —— #
default_posts = [
    {
        "id": 1,
        "title": "帖子标题1",
        "content": "帖子内容1",
        "author": "张三",
        "date": "2023-10-01"
    },
    {
        "id": 2,
        "title": "帖子标题2",
        "content": "帖子内容2",
        "author": "李四",
        "date": "2023-10-02"
    },
    {
        "id": 3,
        "title": "帖子标题3",
        "content": "帖子内容3",
        "author": "王五",
        "date": "2023-10-03"
    },
    {
        "id": 4,
        "title": "帖子标题4",
        "content": "帖子内容4",
        "author": "赵六",
        "date": "2023-10-04"
    },
    {
        "id": 5,
        "title": "帖子标题5",
        "content": "帖子内容5",
        "author": "钱七",
        "date": "2023-10-05"
    }
]

user_profiles = {
    "张三": {
        "name": "张三",
        "sex": "男",
        "age": 25,
        "phone": "12500000000",
        "email": "kunkun@qq.com",
        "hobbies": ["唱", "跳", "rap"],
        "job": "前端工程师",
        "motto": "两年半是你的极限，但只是我的开始",
        "nickname": "jigege",
        "website": "https://www.kunkun.com"
    },
    "李四": {
        "name": "李四",
        "sex": "女",
        "age": 22,
        "phone": "12500000001",
        "email": "superidol@qq.com",
        "hobbies": ["唱", "跳", "打篮球"],
        "job": "后端工程师",
        "motto": "我就是我，是颜色不一样的烟火",
        "nickname": "小四",
        "website": "https://www.lisi.com"
    },
}

users = {
    "张三": {
        "username": "张三",
        "password": "123456",
        "email": "kunkun@qq.com",
        "phone": "12500000000",
    },
    "李四": {
        "username": "李四",
        "password": "123456",
        "email": "superidol@qq.com",
        "phone": "12500000001",
    },
}


# ① 获取所有帖子
@app.route("/api/posts", methods=["GET"])
def get_posts():
    return jsonify(read_local_news())


@app.route("/api/login", methods=["POST"])
def login():
    # 获取前端传来的数据 username 和 password
    # 这里使用 Flask 的 request 对象来获取数据
    data = request.get_json()
    username = data.get("username")
    password = data.get("password")
    # 比对用户名和密码
    user = users.get(username)
    if user and user["password"] == password:
        # 伪造的登录逻辑
        return jsonify({"code": 200, "msg": "登录成功", "user": user})
    else:
        return jsonify({"code": 401, "error": "用户名或者密码错误"})


@app.route("/api/logout", methods=["POST"])
def logout():
    # 伪造的登出逻辑
    return jsonify({"code": 200, "msg": "登出成功"})


# ② 获取指定 id 的帖子详情
@app.route("/api/postdetail/<int:post_id>", methods=["GET"])
def get_post_detail(post_id: int):
    posts = read_local_news()
    post = next((post for post in posts if post["id"] == post_id), None)
    if post is None:
        return jsonify({"error": "Not Found"}), 404
    return jsonify(post)


@app.route("/api/profile/<username>", methods=["GET"])
def get_profile(username: str):
    # 伪造的用户数据
    user_data = user_profiles.get(username) or {}
    if user_data:
        return jsonify({
            "code": 200,
            "msg": "获取用户信息成功",
            "data": user_data
        })
    else:
        return jsonify({
            "code": 404,
            "error": "用户不存在",
            "data": {}
        })


@app.route("/health", methods=["GET"])
def health():
    return "ok", 200


if __name__ == "__main__":
    # 0.0.0.0 便于容器或局域网访问；端口与教师端保持一致
    app.run(host="0.0.0.0", port=3000)
